import logging
from flask import request
import os
import logging.handlers
class RequestShoppingFormatter(logging.Formatter):
    '''

    '''
    def format(self, record):
        record.url = request.url  # 需要在日志中记录请求地址
        record.remote_addr = request.remote_addr  # 需要在日志中记录客户端的地址
        return super().format(record)

def create_logger(app):
    '''
    app : flask中的 app
    return:
    '''
    logging_file_dir = app.config['LOGGING_FILE_DIR']#日志的地址
    logging_file_max_bytes = app.config['LOGGING_FILE_MAX_BYTES']#日志的大小
    logging_file_backup = app.config['LOGGING_FILE_BACKUP']#日志的个数
    logging_level = app.config['LOGGING_LEVEL']#日志级别


    #设置日志的输出格式

    # request_formatter = RequestShoppingFormatter(
        # '[%(asctime)s] %(remote_addr)s  请求 %(url)s \t %(levelname)s 在 %(module)s %(lineno)d : %(message)s')
    request_formatter = RequestShoppingFormatter('[%(asctime)s] %(remote_addr)s 请求 %(url)s \t %(levelname)s 在 %(module)s %(lineno)d : %(message)s')
    #如果目录不存在 则创建一个目录
    if os.path.isdir(logging_file_dir):
        pass
    else:
        os.mkdir(logging_file_dir)

    #自定义一个目录和日志文件
    flask_file_handler = logging.handlers.RotatingFileHandler(filename=os.path.join(logging_file_dir,'shopping.log'),
                                                              maxBytes=logging_file_max_bytes,
                                                              backupCount=logging_file_backup)



    #给当前的handler设置格式
    flask_file_handler.setFormatter(request_formatter)


    #得到一个logging对象
    flask_logger = logging.getLogger('Shopping')

    flask_logger.addHandler(flask_file_handler)
    flask_logger.setLevel(logging_level)



    #整个项目需要两个handler
    flask_consle_handler = logging.StreamHandler()
    # flask_consle_handler.setFormatter(logging.Formatter('[(%asctime)s] %(levelname)s %(module)s %(lineno)d : %(message)s'))
    flask_consle_handler.setFormatter(logging.Formatter('[%(asctime)s] %(levelname)s %(module)s %(lineno)d : %('
                                                         'message)s'))
    if app.debug:
        flask_logger.addHandler(flask_consle_handler)
